package com.hhsjdesign.dynamicui.utils

import android.view.View
import com.hhsjdesign.dynamicui.interfaces.IRedDot
import java.lang.ref.WeakReference

//红点管理对象
object RedDotUtil {

    private class RedDotManager private constructor() {
        val viewList: MutableList<WeakReference<View>> = ArrayList()

        companion object {
            val instance = SingletonHolder.holder
        }

        private object SingletonHolder {
            val holder = RedDotManager()
        }
    }

    //注册
    fun registerMsg(view: View) {
        var hasView = false
        RedDotManager.instance.viewList.forEach {
            if (it.get() == view) {
                hasView = true
                return
            }
        }
        if (!hasView) {
            RedDotManager.instance.viewList.add(WeakReference<View>(view))
        }
    }

    //反注册
    fun unRegisterMsg(view: View) {
        var hasView = false
        RedDotManager.instance.viewList.forEach {
            if (it.get() == view) {
                val reference: WeakReference<View> = WeakReference(view)
                RedDotManager.instance.viewList.remove(reference)
                return@forEach
            }
        }
    }

    //通知红点
    /**
     * 消息编码
     */
    fun notifyMsg(tags: List<String>) {
        RedDotManager.instance.viewList.forEach {
            val view = it.get()
            if (view != null) {
                if (view is IRedDot) {
                    view.showRedDot(tags)
                }
            }
        }
    }

    // TODO: 2021/12/13  延时通知红点，可以尝试用协程处理
    fun notifyMsgDuration(tags: List<String>, duration: Int) {

    }

}